package com.hb.trade.api.routine.sms.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.enums.SmsTypeEnum;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionTenderDTO;
import com.hb.core.pojo.project.section.entity.BidSectionTender;
import com.hb.trade.client.center.UserClient;
import com.hb.trade.client.project.ProjectClient;
import com.hb.trade.client.project.SectionClient;
import org.fzzn.core.third.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private SectionClient sectionClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ProjectClient projectClient;
    @Autowired
    private SmsService smsService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String[] split = message.toString().split("&");

        if (split.length == 2) {
                openingRemind(Long.valueOf(split[0]), split[1]);
        }
        System.out.println("过期key===>" + message.toString());
        super.onMessage(message, pattern);
    }

    private void openingRemind(Long sectionId, String template) {
        List<User> userList = new ArrayList<>();
        // 查询要发送短信的投标人
        BidSectionTenderDTO queryParam = new BidSectionTenderDTO();
        queryParam.setSectionId(sectionId);
        List<BidSectionTender> list = sectionClient.listBidSectionTenderBySectionId(queryParam).getData();
        if (!CollUtil.isEmpty(list)) {
            List<Long> ids = list.stream().map(BidSectionTender::getBidderId).collect(Collectors.toList());
            userList = userClient.getByUserIdList(ids).getData();
        }

        // 查询要发送短信的招标人
        AbstractProject abstractProject = projectClient.detailBySectionId(sectionId).getData();
        Long userId = abstractProject.getUserId();
        User user = userClient.getByUserId(userId).getData();

        JSONObject pushData = JSONUtil.createObj().putOpt("name", abstractProject.getProjectName());
        userList.add(user);
        for (User item : userList) {
            smsService.sendSms(item.getPhone(), SmsTypeEnum.OPENING.getTemplate(), pushData);
        }

    }

}